//
//  STFileViewController.m
//  smart_transferor
//
//  Created by wtc on 11-11-2.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "STFileViewController.h"
#import "STFileScreenController.h"
#import "STFileItem.h"
#import "STFileScreenProtocol.h"


@implementation STFileViewController
@synthesize segControl;
@synthesize scrollView;
@synthesize pageControl;
@synthesize screenList, filelist,filelistAll,filelistAudio,filelistImage,filelistVideo;
@synthesize app;
@synthesize absDir;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)initFileList
{
    NSError * error = nil;
    NSArray *files;
    
    files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:&error];
    self.absDir = [[NSBundle mainBundle] bundlePath];
    
    filelistAll = [[NSMutableArray alloc] init];
    for(NSString *filename in files)
    {
        STFileItem * fileItem = [[STFileItem alloc] initWithFileName:filename AndDir:absDir];
        [self.filelistAll addObject:fileItem];
    }
    
    NSString *photodir = [self.absDir stringByAppendingFormat:@"/../../../Media/DCIM/100APPLE"];
    files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:photodir error:&error];
    
    for(NSString *filename in files)
    {
        STFileItem * fileItem = [[STFileItem alloc] initWithFileName:filename AndDir:photodir];
        [self.filelistAll addObject:fileItem];
    }
    
    NSString *docdir = [self.absDir stringByAppendingFormat:@"/../Documents"];
    files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docdir error:&error];
    
    for(NSString *filename in files)
    {
        STFileItem * fileItem = [[STFileItem alloc] initWithFileName:filename AndDir:docdir];
        [self.filelistAll addObject:fileItem];
    }
    
    self.filelist = self.filelistAll;
      
}

- (void)initScreenList
{
    NSMutableArray *screens = [[NSMutableArray alloc] init];
    maxScreens = (self.filelistAll.count + kNumberPerScreen - 1)/ kNumberPerScreen;
    for(unsigned i = 0; i< maxScreens;i++)
    {
        [screens addObject:[NSNull null]];
    }
    self.screenList = screens;
    [screens release];    
}

- (NSMutableArray *) filterFileList:(NSMutableArray *)flist ByType:(int)type
{
    NSMutableArray * newList = [[NSMutableArray alloc] init ];
    
    STFileItem * item;
    for(item in flist)
    {
        if(item.fileType == type)
        {
            [newList addObject:item];
        }
    }
    return newList;
}

- (void) initView
{
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"wood_bg.png"]];
    
    
    scrollView.pagingEnabled = YES;
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;
    
    pageControl.backgroundColor = [UIColor clearColor];
    
    NSArray *segmentTextContent = [NSArray arrayWithObjects: @"All", @"Image", @"Audio", @"Video",nil];
    segControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
    CGRect frame = pageControl.frame;
    frame.origin.x += 20;
    frame.origin.y += frame.size.height;
    frame.size.width -= 40;
    frame.size.height = 30;
    segControl.frame = frame;
    [segControl addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
    segControl.segmentedControlStyle = UISegmentedControlStyleBordered;
    segControl.selectedSegmentIndex = 0;
    
    [self.view addSubview:segControl];
}

- (void) resetViewWhenChangeFileList:(NSMutableArray *)newFilelist
{
    numScreens = (self.filelist.count + kNumberPerScreen - 1)/kNumberPerScreen;
    if(numScreens > maxScreens)
    {
        maxScreens ++;
        [screenList addObject: [NSNull null]];
    }
    
    pageControl.numberOfPages = numScreens;
    
    pageControl.currentPage = 0;
    
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*numScreens,scrollView.frame.size.height);
    
}

- (void)destroyScreens:(NSMutableArray *)slist onScrollView: (UIScrollView *)sv
{
    STFileScreenController * screen;
    for(int i=0;i<slist.count;i++ )
    {
        screen = [slist objectAtIndex:i];
        if((NSNull *)screen == [NSNull null])
        {
            
        }
        else
        {
            //[screen retain];
            [screen.view removeFromSuperview];
            //[screen release];
            [slist replaceObjectAtIndex:i withObject:[NSNull null]];
        }
    }
}

- (void)awakeFromNib
{
    //[super awakeFromNib];
}


- (IBAction)changePage:(id)sender 
{
    int page = pageControl.currentPage;
    
    //[self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    //[self loadScrollViewWithPage:page + 1];
    
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [scrollView scrollRectToVisible:frame animated:YES];
    
    // Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
    pageControlUsed = YES;
}

- (IBAction)returnClicked:(id)sender 
{
    if(app != nil)
    {
        [app quitWithoutSelectionFromFileView:self]; 
    }
}

- (IBAction)changeSegment:(id)sender 
{
    switch (segControl.selectedSegmentIndex) {
        case 0:
        {
            if(filelist != filelistAll)
            {
                filelist = filelistAll;
                [self destroyScreens:screenList onScrollView:scrollView];
                [self resetViewWhenChangeFileList:filelist];
                [self loadScrollViewWithPage:0];
                
                [scrollView scrollRectToVisible:scrollView.frame animated:YES];
            }
            
        }
            break;
        case 1:
        {
            if(filelistImage == nil)
            {
                filelistImage = [self filterFileList:filelistAll ByType:kImage];
            }
            if(filelist != filelistImage)
            {
                filelist = filelistImage;
                [self destroyScreens:screenList onScrollView:scrollView];
                [self resetViewWhenChangeFileList:filelist];
                [self loadScrollViewWithPage:0];
                
                [scrollView scrollRectToVisible:scrollView.frame animated:YES];
            }
        }
            
            break;
        case 2:
        {
            if(filelistAudio == nil)
            {
                filelistAudio = [self filterFileList:filelistAll ByType:kAudio];
            }
            if(filelist != filelistAudio)
            {
                filelist = filelistAudio;
                [self destroyScreens:screenList onScrollView:scrollView];
                [self resetViewWhenChangeFileList:filelist];
                [self loadScrollViewWithPage:0]; 
                [scrollView scrollRectToVisible:scrollView.frame animated:YES];
            }
        }
            break;
        case 3:
        {
            if(filelistVideo == nil)
            {
                filelistVideo = [self filterFileList:filelistAll ByType:kVideo];
            }
            if(filelist != filelistVideo)
            {
                filelist = filelistVideo;
                [self destroyScreens:screenList onScrollView:scrollView];
                [self resetViewWhenChangeFileList:filelist];
                [self loadScrollViewWithPage:0];
                [scrollView scrollRectToVisible:scrollView.frame animated:YES];
            }
        }
            break;
        default:
            break;
    }
}

- (void) insertItem:(STFileItem *)item
{
    if (item == nil)
    {
        return;
    }
    [item retain];
    [filelistAll addObject:item];
    if(item.fileType == kImage)
    {
        [filelistImage addObject:item];
    }
    else if(item.fileType == kVideo)
    {
        [filelistVideo addObject:item];
    }
    else if(item.fileType == kAudio)
    {
        [filelistAudio addObject:item];
    }
    
    [self drawNewItem:item];
}

- (void) drawNewItem:(STFileItem *)item
{
    int seg = segControl.selectedSegmentIndex;
    
    switch (seg) {
        case 0:
            if (filelistAll.count%kNumberPerScreen == 0) 
            {
                [self resetViewWhenChangeFileList:filelistAll];
                [self loadScrollViewWithPage:numScreens -1 ];
            }
            else if(pageControl.currentPage == numScreens - 1)
            {
                [self loadScrollViewWithPage:numScreens-1];    
            }
            break;
        case 1:
            if(item.fileType == kImage)
            {
                if (filelistImage.count%kNumberPerScreen == 0) 
                {
                    [self resetViewWhenChangeFileList:filelistImage];
                    [self loadScrollViewWithPage:numScreens -1 ];
                }
                else if(pageControl.currentPage == numScreens - 1)
                {
                    [self loadScrollViewWithPage:numScreens-1];    
                }
            }
            break;
        case 2:
            if (item.fileType == kAudio)
            {
                if (filelistAudio.count%kNumberPerScreen == 0) 
                {
                    [self resetViewWhenChangeFileList:filelistAudio];
                    [self loadScrollViewWithPage:numScreens -1 ];
                }
                else if(pageControl.currentPage == numScreens - 1)
                {
                    [self loadScrollViewWithPage:numScreens-1];    
                }
            }
            break;
        case 3:
            if(item.fileType == kVideo)
            {
                if (filelistVideo.count%kNumberPerScreen == 0) 
                {
                    [self resetViewWhenChangeFileList:filelistVideo];
                    [self loadScrollViewWithPage:numScreens -1 ];
                }
                else if(pageControl.currentPage == numScreens - 1)
                {
                    [self loadScrollViewWithPage:numScreens-1];    
                }
            }
            break;
        default:
            break;
    }
}

- (void)loadScrollViewWithPage:(int)page
{
    if(page < 0)
    {
        return;
    }
    if(page >= numScreens)
    {
        return;
    }
    
    STFileScreenController * screen = [screenList objectAtIndex:page];
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width*page;
    frame.origin.y = 0;
    
    if((NSNull *)screen == [NSNull null])
    {
        screen = [[STFileScreenController alloc] initWithNibName:@"STFileScreenController" bundle:nil];
        screen.view.backgroundColor = [UIColor clearColor];
        [screen initWithPage:page In:self.filelist FromView:self App:app];
        screen.view.frame = frame;
        [scrollView addSubview:screen.view];
        [screenList replaceObjectAtIndex:page withObject:screen];
        [screen release];
    }   
}

- (void)scrollViewDidScroll:(UIScrollView *)sender;
{
    if (pageControlUsed)
    {
        // do nothing - the scroll was initiated from the page control, not the user dragging
        return;
    }
	
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    //[self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    //[self loadScrollViewWithPage:page + 1];    
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    pageControlUsed = NO;
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    pageControlUsed = NO;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initView];
    [self initFileList];
    [self initScreenList];
    [self resetViewWhenChangeFileList:filelist];
    [self loadScrollViewWithPage:0];
    /*
    [self initFileList];
    [self initScreenList];
    // Do any additional setup after loading the view from its nib.
    [self initFileList];
    [self initScreenList];
    scrollView.pagingEnabled = YES;
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;*/
    
    
    
    
    //CGRect frame = scrollView.frame;
    //frame.size.width = self.screenList.count * scrollView.frame.size.width;
    //scrollView.frame = frame;
    
    /*pageControl.numberOfPages = self.screenList.count;
    pageControl.currentPage = 0;
    [self loadScrollViewWithPage:0];*/
    /*pageControl.backgroundColor = [UIColor clearColor];
    //[self loadScrollViewWithPage:1];
    */
    

}

- (void)viewDidUnload
{
    [self setScrollView:nil];
    [self setPageControl:nil];
    [self setSegControl:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [scrollView release];
    [pageControl release];
    [segControl release];
    for(STFileItem * item in filelistAll)
    {
        [item release];
    }
    [filelistAll release];
    [filelistAudio release];
    [filelistVideo release];
    [filelistImage release];
    [screenList release];
    self.absDir = nil;
    [super dealloc];
}
@end
